<template>
	<view class="bg-white">
		<uni-nav-bar dark :fixed="true" shadow background-color="#007AFF" status-bar left-icon="left" left-text="返回"
			title="盲板作业登记" @clickLeft="back" />

		<!-- 基础表单校验 -->
		<uni-forms ref="valiForm" :rules="rules" :modelValue="model">
			<uni-forms-item label="作业编号" label-width="120px" required name="number">
				<uni-easyinput v-model="model.number" placeholder="请输入作业编号" disabled/>
			</uni-forms-item>
			<uni-forms-item label="申请时间" label-width="120px" name="applyTime">
				<uni-datetime-picker type="datetime" v-model="model.applyTime" format="yyyy-MM-dd HH:mm:ss"/>
			</uni-forms-item>
			<uni-forms-item label="许可证申请人" label-width="120px" required name="applicant">
				<uni-easyinput v-model="model.applicantText" placeholder="请输入许可证申请人" disabled/>
				<!-- <uni-easyinput v-model="model.applicant" placeholder="请输入许可证申请人" disabled/> -->
			</uni-forms-item>
			<uni-forms-item label="装置" label-width="120px" required name="device">
				<uni-data-select v-model="model.device" :localdata="riskDeviceList" @change="changeRiskDevice"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="单元" label-width="120px" required name="cell" v-if="model.device != null">
				<uni-data-select v-model="model.cell" :localdata="riskUnitList"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="作业部位" label-width="120px" required name="position">
				<uni-easyinput v-model="model.position" placeholder="请输入作业部位" />
			</uni-forms-item>
			<uni-forms-item label="作业地点" label-width="120px" required name="locations">
				<uni-easyinput v-model="model.locations" placeholder="请输入作业地点" />
			</uni-forms-item>
			
			<!-- 盲板作业 -->
			<uni-forms-item label="盲板作业类型" label-width="120px" required name="blindPlateJobType">
				<uni-data-checkbox v-model="model.blindPlateJobType" :localdata="blindplatejobTypeList"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item label="设备管道名称" label-width="120px" required name="equipmentPipeName">
				<uni-easyinput v-model="model.equipmentPipeName" placeholder="请输入设备管道名称" />
			</uni-forms-item>
			<uni-forms-item label="设备原有介质" label-width="120px" required name="equipmentNativeMedium">
				<uni-easyinput v-model="model.equipmentNativeMedium" placeholder="请输入设备原有介质" />
			</uni-forms-item>
			<uni-forms-item label="设备温度" label-width="120px" required name="equipmentTemperature">
				<uni-easyinput v-model="model.equipmentTemperature" placeholder="请输入设备温度" />
			</uni-forms-item>
			<uni-forms-item label="设备压力" label-width="120px" required name="equipmentPressure">
				<uni-easyinput v-model="model.equipmentPressure" placeholder="请输入设备压力" />
			</uni-forms-item>
			<uni-forms-item label="盲板材质" label-width="120px" required name="blindSheet">
				<uni-easyinput v-model="model.blindSheet" placeholder="请输入盲板材质" />
			</uni-forms-item>
			<uni-forms-item label="盲板规格" label-width="120px" required name="blindPlateSpecification">
				<uni-easyinput v-model="model.blindPlateSpecification" placeholder="请输入盲板规格" />
			</uni-forms-item>
			<uni-forms-item label="盲板编号" label-width="120px" required name="blindPlateNumber">
				<uni-easyinput v-model="model.blindPlateNumber" placeholder="请输入盲板编号" />
			</uni-forms-item>
			<uni-forms-item label="盲板位置图" label-width="120px" required name="openCircuitImg">
				<!-- <uni-easyinput v-model="model.openCircuitImg" placeholder="请输入断路地段示意图及相关说明" /> -->
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
					 <image :src="imgList[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red radius" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="ChooseImage" v-if="imgList.length<1">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</uni-forms-item>
			
			
			<uni-forms-item label="施工单位" label-width="120px" required name="operationCompany">
				<uni-easyinput v-model="model.operationCompany" placeholder="请输入施工单位" disabled/>
				<button class="mini-btn" type="info" size="mini" @click="activeKeyCompany('1')">企内单位</button>
				<button class="mini-btn" type="info" size="mini" @click="activeKeyCompany('2')">承包商</button>
			</uni-forms-item>
			<uni-forms-item label="作业负责人" label-width="120px" required name="constructionMan">
				<uni-easyinput v-model="model.constructionMan" placeholder="请输入作业负责人" disabled/>
				<button class="mini-btn" type="info" size="mini" @click="activeKeyOperator('9')">企内单位</button>
				<button class="mini-btn" type="info" size="mini" @click="activeKeyOperator('10')">承包商</button>
			</uni-forms-item>
			<uni-forms-item label="作业内容" label-width="120px" required name="content">
				<uni-easyinput type="textarea" v-model="model.content" placeholder="请输入作业内容" />
			</uni-forms-item>
			<uni-forms-item label="作业人" label-width="120px" required name="operatorAndCode">
				<uni-easyinput v-model="model.operatorAndCode" placeholder="请输入作业人" disabled/>
				<button class="mini-btn" type="info" size="mini" @click="activeKeyOperator('11')">企内单位</button>
				<button class="mini-btn" type="info" size="mini" @click="activeKeyOperator('12')">承包商</button>
			</uni-forms-item>
			<uni-forms-item label="企内监护人" label-width="120px" required name="companyGuardian">
				<uni-easyinput v-model="model.companyGuardian" placeholder="请输入企内监护人" disabled/>
				<button class="mini-btn" type="info" size="mini" @click="activeKeyOperator('13')">查询</button>
			</uni-forms-item>
			<uni-forms-item label="施工单位监护人" label-width="120px" required name="constructionGuardian">
				<uni-easyinput v-model="model.constructionGuardian" placeholder="请输入施工单位监护人" disabled/>
				<button class="mini-btn" type="info" size="mini" @click="activeKeyOperator('7')">企内单位</button>
				<button class="mini-btn" type="info" size="mini" @click="activeKeyOperator('8')">承包商</button>
			</uni-forms-item>
			<uni-forms-item label="作业计划开始时间" label-width="120px" name="planStartDate">
				<uni-datetime-picker type="datetime" v-model="model.planStartDate" />
			</uni-forms-item>
			<uni-forms-item label="作业结束时间" label-width="120px" name="planEndDate">
				<uni-datetime-picker type="datetime" v-model="model.planEndDate" />
			</uni-forms-item>
			<uni-forms-item label="关联的其他特殊作业及安全作业票编号" label-width="120px" required name="relevanceNumber">
				<uni-easyinput v-model="model.relevanceNumber" placeholder="请输入关联的其他特殊作业及安全作业票编号" />
				<button class="mini-btn" type="info" size="mini" @click="activeKeyOperator('14')">查询</button>
			</uni-forms-item>
			<uni-forms-item label="作业原因" label-width="120px" required name="jobReasonList">
				<uni-data-checkbox mode="tag" multiple v-model="model.jobReasonList" :localdata="jobReasonList" @change=""></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item label="风险辨识结果" label-width="120px" required name="riskIdentificationResultList">
				<uni-data-checkbox mode="tag" multiple v-model="model.riskIdentificationResultList" :localdata="riskIdentificationResultList"></uni-data-checkbox>
			</uni-forms-item>
			<!-- <uni-forms-item label="作业所属单位负责人" label-width="120px" required name="operationChargePerson">
				<uni-easyinput v-model="model.operationChargePerson" placeholder="请输入作业所属单位负责人" disabled/>
				<button class="mini-btn" type="info" size="mini" @click="activeKeyOperator('15')">查询</button>
			</uni-forms-item> -->
			<!-- <uni-forms-item label="定位" label-width="120px" name="orientation">
				<uni-easyinput v-model="model.orientation" placeholder="请输入定位" disabled/>
			</uni-forms-item> -->
		</uni-forms>
		<button type="primary" loading="true" @click="submit('valiForm')">生成票据</button>
	</view>
</template>

<script>
	import moment from 'moment';
	import api from '@/api/api.js'
	import { ACCESS_TOKEN,USER_NAME,USER_INFO } from "@/common/util/constants"
	export default {
		data() {
			return {
				model: {
					riskIdentificationResultList: [],
					jobReasonList: [],
				},
				// 校验规则
				rules: {
					number: {
						rules: [{
							required: true,
							errorMessage: '作业证编号不能为空'
						}]
					},
					content: {
						rules: [{
							required: true,
							errorMessage: '作业内容不能为空'
						}]
					},
					riskDeviceId: {
						rules: [{
							required: true,
							errorMessage: '装置不能为空'
						}]
					},
					riskUnitId: {
						rules: [{
							required: true,
							errorMessage: '单元不能为空'
						}]
					},
					jobType: {
						rules: [{
							required: true,
							errorMessage: '作业类型不能为空'
						}]
					},
					planStartDate: {
						rules: [{
							required: true,
							errorMessage: '作业开始时间不能为空'
						}]
					},
					planEndDate: {
						rules: [{
							required: true,
							errorMessage: '作业结束时间不能为空'
						}]
					},
					operatorAndCode: {
						rules: [{
							required: true,
							errorMessage: '作业人不能为空'
						}]
					},
					applicant: {
						rules: [{
							required: true,
							errorMessage: '作业申请人不能为空'
						}]
					},
					operationChargePerson: {
						rules: [{
							required: true,
							errorMessage: '作业所属单位负责人不能为空'
						}]
					},
					jobReasonList: {
						rules: [{
							required: true,
							errorMessage: '作业原因不能为空'
						}]
					},
					riskIdentificationResultList: {
						rules: [{
							required: true,
							errorMessage: '风险辨识结果不能为空'
						}]
					},
					companyGuardian: {
						rules: [{
							required: true,
							errorMessage: '公司监护人不能为空'
						}]
					},
					constructionGuardian: {
						rules: [{
							required: true,
							errorMessage: '施工单位监护人不能为空'
						}]
					},
				},
				dictCodeList: {
					dictCodeRiskDevice: "tb_base_risk_device,name,id",
					dictCodeRiskUnit: "tb_base_risk_unit,risk_unit_name,id",
					dictCodeJobBlindplateType: "blindplatejobType",
					dictCodeJobReasonLevel: "jobReason",
					dictCodeJobRiskIdentificationLevel: "jobRiskIdentification"
				},
				url:{
					getUserListAll: "/sys/user/listAll",
					uploadUrl: "/sys/common/upload",
					queryJobCode: "/TbJobTicket/tbJobTicket/queryJobCode",
				},
				riskDeviceList: [], //装置list
				riskUnitList: [],//单元list
				blindplatejobTypeList: [],//盲板作业类型
				jobReasonList: [],//作业原因
				riskIdentificationResultList: [],//风险辨识
				operationCompanyType: "",//施工单位节点标识
				operatorType: "",//选择人员是企业内还是承包商节点标识
				imgList: [],
			}
		},
		components: {},
		mounted() {
			this.queryJobCode();//获取电子作业票编号
			this.initRiskDeviceList();
			this.initBlindplateTypeList();
			this.initJobReasonList();
			this.initjobRiskIdentificationList();
			this.initDefaultModelValue();
		},
		methods: {
			queryJobCode(){
				api.queryJobCode().then(response =>{
					if(response.data.success){
						this.model.number = response.data.result
					}
				})
			},
			initDefaultModelValue(){
				/* 动火作业：1，临时用电：2，吊装作业：3，盲板抽堵：4，动土作业：5，
				断路作业：6，受限空间作业：7，高处作业：8，通用作业：9，带压堵漏：10.
				1,3,8对应的是动火，吊装，高处，这三个有对应的级别类型，所以而且由于级别字段同所以需要单独处理*/
				const userInfo = uni.getStorageSync(USER_INFO);
				this.model.applyCompany = userInfo.orgCode;//申请单位
				this.model.applicant = userInfo.username
				this.model.applicantText = userInfo.realname;
				this.model.jobType = "4";//动火作业
				this.model.applyTime = moment(new Date).format('YYYY-MM-DD HH:mm:ss');
				this.model.deleted = "0";//动火作业
				console.log("-------this.model-----------"+JSON.stringify(this.model))
			},
			initRiskDeviceList() {
				api.initDictData(this.dictCodeList.dictCodeRiskDevice).then(response =>{
					if(response.data.success){
						this.riskDeviceList = response.data.result
					}
				})
			},
			changeRiskDevice(value) {
				const dictCode = this.dictCodeList.dictCodeRiskUnit + ",device_id='"+ value +"'";
				api.initDictData(dictCode).then(response =>{
					if(response.data.success){
						this.riskUnitList = response.data.result
					}
				})
			},
			initBlindplateTypeList(){
				api.initDictData(this.dictCodeList.dictCodeJobBlindplateType).then(response =>{
					if(response.data.success){
						this.blindplatejobTypeList = response.data.result
					}
				})
			},
			initJobReasonList(){
				api.initDictData(this.dictCodeList.dictCodeJobReasonLevel).then(response =>{
					if(response.data.success){
						this.jobReasonList = response.data.result
					}
				})
			},
			initjobRiskIdentificationList(){
				api.initDictData(this.dictCodeList.dictCodeJobRiskIdentificationLevel).then(response =>{
					if(response.data.success){
						this.riskIdentificationResultList = response.data.result
					}
				})
			},
			selectUserList(val) {//引用用户
				this.nodeValue =val;
				this.$Router.push({
					name: 'selectUserListRadio',
				})
			},
			activeKeyCompany(val) {//引用用户
				console.log("-======val=="+val)
				this.operationCompanyType =val;
				if(val == "1"){
					this.$Router.push({name: 'selectOurCompanyList'})
				}else if(val == "2"){
					this.$Router.push({name: 'selectContractorList'})
				}
			},
			getSelectRowValue(selectRowValue){
				console.log("-=getContractorValue=====data=="+JSON.stringify(selectRowValue))
				if(this.operationCompanyType == "1"){
					this.model.operationCompany = selectRowValue.text
				}else if(this.operationCompanyType == "2"){
					this.model.operationCompany = selectRowValue.name
				}
				this.$forceUpdate();//必须加强制刷新，否则不渲染
			},
			/**
			 * 人员选择
			 */
			activeKeyOperator(val) {
			  this.operatorType = val;
			  /* 7表特殊用的是企业内的监护人组件*/
			  if(val == '1' || val == '3' || val == '5' || val == '9' || val == '11'){
			    this.$Router.push({name: 'selectUserListCheckBox'})
			  }else if(val == "2" || val == '4' || val == '6' || val == '8' || val == '10'){
			    this.$Router.push({name: 'selectContractorPersonList'})
			  }else if(val == "7" ||val == "13"){
			    this.$Router.push({name: 'selectOurCompanyGuardianHeadquartersList'})
			  }else if(val == "12"){
			    this.$Router.push({name: 'selectContractorPersonCertificateList'})
			  }else if(val == "14"){
			    this.$Router.push({name: 'selectRelevanceJobTicketCheckBox'})
			  }
			},
			getUserCheckBoxValue(selectedRows) {
				console.log("====selectedRows========="+selectedRows)
				const selectedRowNames = []
				selectedRows.forEach(item =>{
				  selectedRowNames.push(item.name)
				})
				
				console.log("====selectedRowNames==========="+selectedRowNames)
				if(this.operatorType =="1" || this.operatorType == "2"){
				  this.model.liftingOperator= selectedRowNames.toString();
				}else if(this.operatorType == "3" || this.operatorType == "4"){
				  this.model.liftingSisot = selectedRowNames.toString();
				}else if(this.operatorType == "5" || this.operatorType == "6"){
				  this.model.liftingCommandingOfficer = selectedRowNames.toString();
				}else if(this.operatorType == "7" || this.operatorType == "8"){
				  this.model.constructionGuardian = selectedRowNames.toString();
				}else if(this.operatorType == "9" || this.operatorType == "10"){
				  this.model.constructionMan = selectedRowNames.toString();
				}else if(this.operatorType == "11" || this.operatorType == "12"){
				  this.model.operatorAndCode = selectedRowNames.toString();
				}else if(this.operatorType == "13"){
				  this.model.companyGuardian = selectedRowNames.toString();
				}else if(this.operatorType == "14"){
				  this.model.relevanceNumber = selectedRowNames.toString();
				}
				this.$forceUpdate();//必须加强制刷新，否则不渲染
			},
			getUserCertificateCheckBoxValue(selectedRows) {
				const selectedOurCompanyPersonnelCertificates = []
				selectedRows.forEach(item =>{
				  selectedOurCompanyPersonnelCertificates.push(item.name)
				})
				
				console.log("====selectedOurCompanyPersonnelCertificates==========="+selectedOurCompanyPersonnelCertificates)
				if(this.operatorType == "12"){
				  this.model.operatorAndCode = selectedOurCompanyPersonnelCertificates.toString();
				}
				this.$forceUpdate();//必须加强制刷新，否则不渲染
			},
			ChooseImage() {
				var that=this;
				uni.chooseImage({
					count: 4, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						that.$http.upload(that.$config.apiUrl+that.url.uploadUrl, {
								filePath: res.tempFilePaths[0],
								name: 'file'
							})
							.then(res => {
								that.model.breakGroundImg = res.data.message;
							})
							.catch(err => {
								that.$tip.error(err)
							});
						this.imgList = res.tempFilePaths
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '删除图片',
					content: '确定要删除这个图片吗？',
					cancelText: '取消',
					confirmText: '确认',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			// 获取上传状态
			// select(selectFile){
			// 	selectFile.tempFilePaths.forEach(fileItem =>{
			// 		this.$tip.loading();
			// 		const fileParams = {filePath: fileItem,name: 'file'}
			// 		api.uploadFiles(fileParams).then(response =>{
			// 			this.$tip.loaded();
			// 			if(response.data.success){
			// 				if(this.model.img){
			// 					this.model.img = this.model.img + "," + res.data.message;
			// 				}else{
			// 					this.model.img = response.data.message
			// 				}
			// 			}
			// 		})
			// 	})
			// },
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
			submit(ref) {
				console.log("-------this.model-----------"+JSON.stringify(this.model))
				this.$refs[ref].validate().then(res => {
					api.saveGenerateTickets(this.model).then(response =>{
						if(response.data.success){
							this.$tip.success("添加成功!")
							this.$Router.replace({name:'index'})
						}else{
							this.$tip.error("添加失败!");
						}
					})
				}).catch(err => {
					this.$tip.error("请填写必填项!");
				})
			},
		}
	} 
</script>

<style lang="scss">
	.bg-white {
		background-color: #fff;
	}

	.form-item {
		display: flex;
		align-items: left;
	}
	@mixin flex {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}
	@mixin height {
		/* #ifndef APP-NVUE */
		height: 100%;
		/* #endif */
		/* #ifdef APP-NVUE */
		flex: 1;
		/* #endif */
	}
	.popup-content {
		@include flex;
		align-items: center;
		justify-content: center;
		padding: 15px;
		width: 300px;
		height: 400px;
		background-color: #fff;
	}
	.popup-height {
		@include height;
		width: 200px;
	}
	.example-body {
		padding: 10px;
		padding-top: 0;
	}
</style>